package logs

import (
	"log"
	"os"
	"runtime"
	"strconv"
	"sync"
)

var (
	Trace   *log.Logger // 记录所有日志
	Info    *log.Logger // 重要的信息
	Warning *log.Logger // 需要注意的信息
	Error   *log.Logger // 非常严重的问题
)

const logPath  = "log/willow.log"

var file  *os.File
var once sync.Once
func init() {
	once.Do(func() {
		var err error
		file, err = os.OpenFile(logPath,
			os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
		if err != nil {
			log.Fatalln("Failed to open error log file:", err)
		}
	})
}

func TraceLog(str string)  {
	Trace = log.New(file,
		"TRACE: ",
		log.Ldate|log.Ltime)
	_, file, line, ok := runtime.Caller(1)
	if ok {
		Trace.Println(file+":"+strconv.FormatInt(int64(line),10)+": "+str)
	} else {
		Trace.Println(str)
	}
}

func InfoLog(str string)  {
	Info = log.New(file,
		"INFO: ",
		log.Ldate|log.Ltime)
	_, file, line, ok := runtime.Caller(1)
	if ok {
		Info.Println(file+":"+strconv.FormatInt(int64(line),10)+": "+str)
	} else {
		Info.Println(str)
	}
}

func WarningLog(str string)  {
	Warning = log.New(file,
		"WARNING: ",
		log.Ldate|log.Ltime)
	_, file, line, ok := runtime.Caller(1)
	if ok {
		Warning.Println(file+":"+strconv.FormatInt(int64(line),10)+": "+str)
	} else {
		Warning.Println(str)
	}
}

func ErrorLog(str string)  {
	Error = log.New(file,
		"ERROR: ",
		log.Ldate|log.Ltime)
	_, file, line, ok := runtime.Caller(1)
	if ok {
		Error.Println(file+":"+strconv.FormatInt(int64(line),10)+": "+str)
	} else {
		Error.Println(str)
	}
}